<?php

declare (strict_types=1);

namespace app\api\model\store\shop;

use app\api\model\Order as OrderModel;
use app\api\model\User;
use app\api\service\User as UserService;
use app\api\model\store\shop\Clerk as ClerkModel;
use app\common\model\store\shop\Order as ShopOrderModel;

/**
 * 商家门店核销订单记录模型
 * Class Order
 * @package app\api\model\store\shop
 */
class Order extends ShopOrderModel
{
    /**
     * 获取用户订单详情页数据 [需验证核销员身份]
     * @param int $orderId 订单ID
     * @return \app\api\model\Order|array|false|null
     * @throws \cores\exception\BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getUserOrderDetail(int $orderId)
    {
        // 获取当前店员信息
//        $userId = UserService::getCurrentLoginUserId();
//        if (!ClerkModel::getClerkInfo($userId)) {
//            return false;
//        }
        // 查询当前的订单信息
        return OrderModel::getUserOrderDetail($orderId, false);
    }

    /**
     * 确认订单核销
     * @param int $orderId 订单ID
     * @return bool
     * @throws \cores\exception\BaseException
     */
    public function extract(int $orderId): bool
    {
        // 获取当前店员信息
        $userId = UserService::getCurrentLoginUserId();
        $clerkInfo = ClerkModel::getClerkInfo($userId);
        // 查询当前的订单信息
        $orderInfo = OrderModel::getDetail($orderId, [], false);
        // 验证店员信息是否为指定门店的核销员
        ClerkModel::checkAuthority($clerkInfo, (int)$orderInfo['extract_shop_id']);
        // 确认并核销
        if (!$orderInfo->confirmExtract((int)$clerkInfo['clerk_id'], true)) {
            $this->error = $orderInfo->getError();
            return false;
        }
        return true;
    }

    public function pay(array $params)
    {
        $userId = UserService::getCurrentLoginUserId();
        $userModel = new User();
        $user = $userModel->get($userId);
        if($user->balance < $params['money']){
             $this->error = "余额不足";
             return false;
        }
        $data = [
            "shop_id" => $params["shop_id"],
            "uid" => $userId,
            "create_time" => time(),
            "store_id" => self::$storeId,
            "money" => $params['money']
        ];
        $this->startTrans();
        if($this->save($data)){
            $user->balance = $user->balance-$params['money'];
            $user->save();
            $this->commit();
            return $this->id;
        }else{
            $this->error = "核销失败";
            $this->rollback();
            return false;
        }
    }
}